package com.zretc.security.feign;

import com.zretc.common.constant.SecurityConstant;
import com.zretc.common.util.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import javax.servlet.http.HttpServletRequest;

public class AuthFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获得请求对象
        HttpServletRequest request =
                ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
        //从原始请求中 获得白名单信息
        String white = request.getHeader(SecurityConstant.WHITE_HEADER_NAME);
        //如果当前请求在白名单中
        if(StringUtils.hasText(white)){
            //将白名单信息继续后续链路传递
            requestTemplate.header(SecurityConstant.WHITE_HEADER_NAME,white);
        }

        //传递key
        String key = request.getHeader(SecurityConstant.AUTHENTICATION_KEY);
        if(StringUtils.hasText(key)){
            //将白名单信息继续后续链路传递
            requestTemplate.header(SecurityConstant.AUTHENTICATION_KEY,key);
        }
    }
}
